local socket = require("socket")


package.path = package.path ..';../?.lua'
local tool = require('lib/tool')

local Client = tool.class('Client')
function Client:Ctor()
    self.idseed = 0
end

function Client:connect(host, port, timeout)
    self.socket = assert(socket.connect(host, port))
    self.socket:settimeout(timeout)
end

function Client:onUpdate()
    local recvt, sendt, status
    recvt, sendt, status = socket.select({self.socket}, nil, 1)
    while #recvt > 0 do
        local response, receive_status = self.socket:receive()
        if receive_status ~= "closed" then
            if response then
                recvt, sendt, status = socket.select({self.socket}, nil, 1)
                self:onReceived(response)
            end
        else
            self:onDisConnect()
        end
    end
end

function Client:request(message,callBack, timeout)
    local code =  self:regist(callBack, timeout)
    self.socket:send(message)
end

function Client:onReceived(msg)
    error("aplay by the delegate")
    print("onReceived")
    print(msg)
end

function Client:decodeMsg(telegram)
    return self.callBack,telegram
end

function Client:regist(callBack)
    self.callBack = callBack
    self.idseed = self.idseed +1
    return self.idseed
end

function Client:onDisConnect()
    error("onDisConnect")
end

return Client
